﻿using System.Linq.Expressions;
using Entity.Models;
using IRepositorys;
using IServices;
using SqlSugar;

namespace Services;

public class MenuService : BaseService<SysMenu>, IMenuService
{
    private readonly IBaseRepository<SysMenu> repository;

    public MenuService(IBaseRepository<SysMenu> repository)
        : base(repository)
    {
        this.repository = repository;
    }

    public SysMenu GetMenuById(int id)
    {
        return repository.GetById(id);
    }

    /// <summary>
    ///     获取菜单列表
    /// </summary>
    /// <param name="searchText"></param>
    /// <returns></returns>
    public List<SysMenu> GetMenuList(string searchText = "")
    {
        // 首先获取符合条件的父级菜单。
        var parentMenus = repository.GetList(x =>
            string.IsNullOrEmpty(searchText)
            || x.MenuHeader.Contains(searchText)
            || x.TargetView.Contains(searchText)
        );

        // 然后获取符合条件的子菜单。
        var childMenus = repository.GetList(x =>
            SqlFunc
                .Subqueryable<SysMenu>()
                .Where(y =>
                    y.ParentId == x.Id
                    && (y.MenuHeader.Contains(searchText) || y.TargetView.Contains(searchText))
                )
                .Count() > 0
        );
        // 合并父级菜单和子菜单。
        var result = parentMenus.Union(childMenus).ToList();
        return result;
    }

    public List<SysMenu> GetMenuList(Expression<Func<SysMenu, bool>> whereLambda)
    {
        return repository.GetList(whereLambda);
    }
}
